package dp1.titandevelop.titano.view;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import dp1.titandevelop.titano.persistent.*;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import org.apache.cayenne.DataObjectUtils;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SelectQuery;

//package dp1.titandevelop.titano.view;

/**
 *
 * @author andres
 */
public class PanelTabla extends javax.swing.JPanel {

    
    // genero mi modelo para poder interactuar con la tabla
    private List<Parametro> listaParametros; // lo que agregue aqui aparece en la tabla
    
    private AbstractTableModel modelo = new AbstractTableModel () { // usando una clase anonima
        // colocando los titulos de las columnas
        String [] titles = {"Ruta Auditoria", "Nombre del Software", "Algo", "Elem"};
        Class<?>[] colTypes = {String.class, String.class, Boolean.class, JButton.class};
        public int getRowCount() {
            return listaParametros.size(); // cuantos registros (filas)
        }

        public int getColumnCount() {
            return 4; // cuantas columnas
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            String res=null;
            Parametro p = listaParametros.get(rowIndex);
            switch(columnIndex){
                case 0: res = p.getRutaauditoria(); break;
                case 1: res = p.getNombresoftware(); break;
                case 2: if (p.getEstado() == 1) 
                            return Boolean.TRUE;
                        else return Boolean.FALSE;
                case 3: final JButton button = new JButton(titles[columnIndex]);
                        button.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent arg0) {
                                //JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(button), 
                                //        "Button clicked for row "+rowIndex);
                                System.out.println("Hola todo el mundo");
                            }
                        });
                        button.setEnabled(true);
                        return button;
                    

            }
            return res;
        }

        public String getColumnName(int col){
            return titles[col];
        }
        
        @Override 
        public Class<?> getColumnClass(int columnIndex) {
            return colTypes[columnIndex];
        }
        
        
        
        
       

//        @Override
//        public Class getColumnClass(int c) {
//            return getValueAt(0, c).getClass();
//        }

    };
    /**
     * Creates new form PanelTabla
     */
    public PanelTabla() {
        initComponents();
        // ahora la consulta se hace aqui, esto ahorrara memoria
        ObjectContext context = DataContext.createDataContext();
        Parametro parametro = context.newObject(Parametro.class);
        
        // esto podria meterse en un metodo
        SelectQuery consulta = new SelectQuery(Parametro.class);
        this.listaParametros = context.performQuery(consulta);
     
        this.jTable1.setModel(this.modelo);
        TableCellRenderer br = new TableCellRenderer() {
            @Override 
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JButton button = (JButton)value;
                return button;  
            }
        };
        
        this.jTable1.getColumn("Elem").setCellRenderer(br);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Falsa insercion");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Falsa Borradura");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Borrate");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(17, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
       
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // TODO add your handling code here:
        Parametro p = new Parametro();
        p.setNombresoftware("hiiii");
        p.setRutaauditoria("algooo");
    
        this.listaParametros.add(p);
        this.modelo.fireTableChanged(null); // refresca la gui  
    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        this.listaParametros.remove(this.jTable1.getSelectedRow());
        this.modelo.fireTableChanged(null); // refresca la gui

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        ObjectContext context = DataContext.createDataContext();
        
        // saco lo que escogi en la tabla
        Parametro p = this.listaParametros.get(this.jTable1.getSelectedRow());
        
        // lo busco en la bd
        Expression qualifier = ExpressionFactory.matchExp(Parametro.IDPARAMETRO_PK_COLUMN, p.getIdparametro());
        SelectQuery select = new SelectQuery(Parametro.class, qualifier);
        Parametro param = (Parametro) DataObjectUtils.objectForQuery(context, select);
        
        // lo borro y confirmo la borradura
        context.deleteObject(param);
        context.commitChanges();
        
        // actualizo todo
        // esto podria meterse en un metodo
        SelectQuery consulta = new SelectQuery(Parametro.class);
        this.listaParametros = context.performQuery(consulta);
        
        
        this.modelo.fireTableChanged(null); // refresca la gui

    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
